package cn.chanel.mall.admin.controller;

import cn.chanel.mall.admin.vo.AdminOrderEnumVO;
import cn.chanel.mall.enums.OrderStatusEnum;
import cn.chanel.mall.enums.ResultEnum;
import cn.chanel.mall.exception.MallException;
import cn.chanel.mall.service.OrderService;
import cn.chanel.mall.utils.EnumUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {
    @Resource
    private OrderService orderService;

    @GetMapping("list")
    public ModelAndView list(@RequestParam(required = false, defaultValue = "") String key,
                             Map<String, Object> map) {
        if(StringUtils.hasText(key)){
            map.put("allOrders", orderService.getAllOrdersByKey(key));
        }else {
            map.put("allOrders", orderService.getAllOrders());
        }
        return new ModelAndView("/admin/order/list", map);
    }

    @GetMapping("detail")
    public ModelAndView getOne(@RequestParam(required = false, defaultValue = "") String id,
                               Map<String, Object> map) {
        if(StringUtils.hasText(id)){
            map.put("adminOrderVO", orderService.getOrderVOById(id));
            map.put("allOrderStatus", convertEnums(EnumUtil.getAllEnums(OrderStatusEnum.class)));
            return new ModelAndView("/admin/order/update", map);
        }else {
            throw new MallException(ResultEnum.ORDER_INF_ERROR);
        }
    }

    @PostMapping("update")
    public ModelAndView update(@RequestParam String id,
                               @RequestParam int status) {
        if(StringUtils.hasText(id)){
            orderService.updateOrder(id, status);
            return new ModelAndView("redirect:/admin/order/list");
        }else {
            throw new MallException(ResultEnum.ORDER_INF_ERROR);
        }
    }


    private List<AdminOrderEnumVO> convertEnums(OrderStatusEnum[] orderStatusEnums){
        final ArrayList<AdminOrderEnumVO> adminOrderEnumVOS = new ArrayList<>();
        for (OrderStatusEnum e : orderStatusEnums) {
            adminOrderEnumVOS.add(new AdminOrderEnumVO(e.getName(), e.getCode()));
        }
        return adminOrderEnumVOS;
    }
}
